import re


def parse_choice_questions(file, authority, name, label, choice_type):
    pattern = re.compile(
        r'(?P<qid>\d+)[.\(\)（）]\s*(?P<stem>.+)\n+(?P<options>([\(（)]?[A-Z][.\(\)（）]\s*.+\n+){2,})\[(?P<ans>[A-Z]+)\]\n*')
    matches = pattern.finditer(file)

    questions = []

    for qid, match in enumerate(matches):
        data = match.groupdict()
        options = re.findall(r'[A-Z][.\(\)（）]\s*(.+)\n*', data['options'])

        options = {chr(65 + idx): option.strip() for idx, option in enumerate(options)}
        options_cnt = len(options)
        ans = list(data.pop('ans'))
        ans_cnt = len(ans)
        choice = {'type': choice_type, 'options_cnt': options_cnt, 'options': options, 'ans_cnt': ans_cnt, 'ans': ans}

        data.pop('options')
        data['stem'] = data['stem'].strip()
        data['choice'] = choice
        data['qid'] = qid + 1
        data['type'] = 'CQ'
        data['authority'] = authority
        data['name'] = name
        data['label'] = label

        questions.append(data)
    return questions


def parse_blank_questions(file, authority, name, label):
    pattern = re.compile(r'(?P<qid>\d+)[.\(\)（）]\s*(?P<stem>.+)\n+(?P<blank_cnt>\d+)\n+(?P<ans>(.+\n)+)')
    matches = pattern.finditer(file)

    questions = []

    for qid, match in enumerate(matches):
        data = match.groupdict()
        ans = re.findall(r'(.+)\n', data['ans'])

        list(data.pop('ans'))
        data.pop('blank_cnt')
        blank_cnt = len(ans)

        blank = {'ans_cnt': blank_cnt, 'ans': ans}
        data['blank'] = blank
        data['qid'] = qid + 1
        data['type'] = 'FBQ'
        data['authority'] = authority
        data['name'] = name
        data['label'] = label

        questions.append(data)
    return questions
